package com.heima.crm.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.crm.common.contents.CommonMessageContent;
import com.heima.crm.mapper.CrUserMapper;
import com.heima.crm.pojos.entity.TbUser;
import com.heima.crm.pojos.vos.ImportVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserParsing {


    @Resource
    private CrUserMapper crUserMapper;


    public ImportVo pase(MultipartFile excelFile) {
        ImportVo importVo =new ImportVo();
        try (Workbook workbook = new XSSFWorkbook(excelFile.getInputStream())) {
            List<TbUser> list =new ArrayList<>();
            Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一个工作表中
            // 从第二行开始读取数据
            int abnormalData = 0;
            int totalData = 0;
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row != null) {
                    TbUser tbUser = extracted(row);
                    try {
                        CheckData(tbUser);
                    } catch (Exception e) {
                        abnormalData++;
                        totalData++;
                        continue;
                    }
                    list.add(tbUser);
                    //crUserMapper.insert(tbUser);
                    totalData++;
                }
            }
            String kid = CaptchaUtils.temporarySetUser(list);
            importVo.setKid(kid);
            Integer success = totalData-abnormalData;
            if (success<0){
                success=0;
            }
            importVo.setSuccessData(success);
            importVo.setTotalData(totalData);
            importVo.setFailedData(abnormalData);
            String originalFilename = excelFile.getOriginalFilename();
            importVo.setFileName(originalFilename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return importVo;
    }

    private  void CheckData(TbUser tbUser){
        if (tbUser==null){
            throw new RuntimeException("数据有误");
        }
        String phonenumber = tbUser.getPhonenumber();
        String userName = tbUser.getUserName();
        Integer integer = Math.toIntExact(crUserMapper.selectCount(new LambdaQueryWrapper<TbUser>()
                .eq(TbUser::getPhonenumber, phonenumber)
                .eq(TbUser::getUserName, userName)));
        if (integer>0){
            throw new RuntimeException("数据有误");
        }
    }


    private static TbUser extracted(Row row) {
        Cell deptId = row.getCell(0); // 部门ID所在的单元格
        Cell username = row.getCell(1); // 用户名称所在的单元格
        Cell nikename = row.getCell(2);//昵称
        Cell userType = row.getCell(3);//用户类型
        Cell phoneNumber = row.getCell(4);//电话号码
        Cell sex = row.getCell(5);//性别
        Cell avatar = row.getCell(6);//头像
        Cell password = row.getCell(7);//密码
        Cell status = row.getCell(8);//状态
        Cell remark = row.getCell(9);//备注
        Cell postId = row.getCell(10);//岗位id
        TbUser tbUser =new TbUser();
        tbUser.setDeptId(convertCellToLong(deptId));
        tbUser.setUserName(convertCellToString(username));
        tbUser.setNickName(convertCellToString(nikename));
        tbUser.setUserType(convertCellToStringWithoutDecimal(userType));
        tbUser.setPhonenumber(convertCellToStringWithoutDecimal(phoneNumber));
        tbUser.setSex(convertCellToStringWithoutDecimal(sex));
        tbUser.setAvatar(convertCellToStringWithoutDecimal(avatar));
        tbUser.setPassword(DigestUtils.md5DigestAsHex((convertCellToStringWithoutDecimal(password)+ CommonMessageContent.PASSWORD_SALT).getBytes()));
        tbUser.setStatus(convertCellToStringWithoutDecimal(status));
        tbUser.setRemark(convertCellToStringWithoutDecimal(remark));
        tbUser.setPostId(convertCellToLong(postId));
        tbUser.setCreateBy(BaseContext.getCurrentId().toString());
        tbUser.setCreateTime(LocalDateTime.now());
        tbUser.setUpdateBy(BaseContext.getCurrentId().toString());
        tbUser.setUpdateTime(LocalDateTime.now());
        return tbUser;
    }

    public static String convertCellToStringWithoutDecimal(Cell cell) {
        String cellValue = "";

        if (cell != null) {
            CellType cellType = cell.getCellType();

            if (cellType == CellType.NUMERIC) {
                double numericValue = cell.getNumericCellValue();
                long intValue = (long) numericValue;
                cellValue = String.valueOf(intValue);
            } else {
                DataFormatter dataFormatter = new DataFormatter();
                cellValue = dataFormatter.formatCellValue(cell);
            }
        }

        return cellValue;
    }

    public static Long convertCellToLong(Cell cell) {
        Long numericValue = null;

        if (cell != null) {
            CellType cellType = cell.getCellType();

            if (cellType == CellType.NUMERIC) {
                numericValue = (long) cell.getNumericCellValue();
            } else if (cellType == CellType.STRING) {
                try {
                    numericValue = Long.parseLong(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    // 处理无法解析为长整型的字符串值
                    e.printStackTrace();
                }
            }
        }

        return numericValue;
    }

    public static String convertCellToString(Cell cell) {
        if (cell == null) {
            return null;
        }

        CellType cellType = cell.getCellType();
        String cellValue;

        if (cellType == CellType.STRING) {
            cellValue = cell.getStringCellValue();
        } else if (cellType == CellType.NUMERIC) {
            cellValue = String.valueOf(cell.getNumericCellValue());
        } else if (cellType == CellType.BOOLEAN) {
            cellValue = String.valueOf(cell.getBooleanCellValue());
        } else if (cellType == CellType.FORMULA) {
            cellValue = cell.getCellFormula();
        } else if (cellType == CellType.BLANK) {
            cellValue = "";
        } else {
            cellValue = cell.toString();
        }

        return cellValue;
    }

}
